package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.heima.user.mapper.ApUserMapper;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto loginDto) {
        log.info("用户信息：{}",loginDto);
        //判断登录用户身份：普通用户 || 游客
        if (!StringUtils.isNotEmpty(loginDto.getPhone()) && !StringUtils.isNotEmpty(loginDto.getPassword())) {
            //根据手机号查询用户
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //用户不存在
            if (apUser == null) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //比对密码
            String inputPassword = DigestUtils.md5DigestAsHex((loginDto.getPassword() + apUser.getSalt()).getBytes());
            if (!inputPassword.equals(apUser.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回jwt数据 data:{user,token}
            Map<String,Object> map = new HashMap();
            //去除敏感数据
            apUser.setPassword(null);
            apUser.setSalt(null);
            map.put("user",apUser);
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            return ResponseResult.okResult(map);
        }else {
            //游客
            //返回jwt数据 data:{user,token}
            HashMap map = new HashMap();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
